package com.resource.project.service.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.resource.project.entity.RespBean;
import com.resource.project.entity.system.MenuRole;
import com.resource.project.entity.system.Role;
import com.resource.base.exception.BadRequestAlertException;
import com.resource.project.mapper.RoleMapper;
import com.resource.project.service.system.service.IMenuRoleService;
import com.resource.project.service.system.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author resource
 * @since 2020-03-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    private IMenuRoleService menuRoleService;

    public List<Role> roles() {
        return roleMapper.roles();
    }

    public int addNewRole(String role, String roleZh) {
        if (!role.startsWith("ROLE_")) {
            role = "ROLE_" + role;
        }
        return roleMapper.addNewRole(role, roleZh);
    }

    public int deleteRoleById(Long rid) {
        return roleMapper.deleteRoleById(rid);
    }

    @Override
    public RespBean addRole(Role role) {
        Role one = getOne(Wrappers.<Role>lambdaQuery().eq(Role::getName, role.getName()));
        if (one!=null){
            throw new BadRequestAlertException("角色名已存在！");
        }
        role.setName("ROLE_"+role.getName());
        if (save(role)) {
            return RespBean.ok();
        }
        return RespBean.error();
    }

    @Override
    public RespBean deleteRole(Long id) {
        //查询关联的菜单
        List<MenuRole> list = menuRoleService.list(Wrappers.<MenuRole>lambdaQuery().eq(MenuRole::getRid, id));
        if (!list.isEmpty()){
            menuRoleService.removeByIds(list.stream().map(MenuRole::getId).collect(Collectors.toList()));
        }
        return removeById(id)?RespBean.ok():RespBean.error();
    }
}
